package main.java.dao.impl;

import main.java.dao.UserDao;
import main.java.domain.User;
import main.java.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class UserDaoImpl implements UserDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    private User find(String sql, String username, String password, String type){
        try{
            User user =  template.queryForObject(
                    sql,
                    new BeanPropertyRowMapper<User>(User.class),
                    username,
                    password
            );

            assert user != null;
            user.setType(type);

            return user;
        }catch (Exception e){
            return null;
        }
    }

    @Override
    public User findUserByStudent(String username, String password) {
        String sql = "select * from stu where username = ? and password = ?";

        return find(sql, username, password, "STUDENT");
    }

    @Override
    public User findUserByTeacher(String username, String password) {
        String sql = "select * from tea where username = ? and password = ?";

        return find(sql, username, password, "TEACHER");
    }

    /**
     * 根据作业id查找所属教师
     * @param {Integer} id
     * @return User
     */
    @Override
    public User findTeacherOfTaskID(int id) {
        String sql = "select id, name, username from tea where id in (select tid from task where ? = task.id)";

        return template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id);
    }

    @Override
    public List<User> findAll() {
        return template.query("select * from stu", new BeanPropertyRowMapper<User>(User.class));
    }
}
